//
//  VCHomeViewController.m
//  VideoCollage
//
//  Created by Mac on 2018/6/19.
//  Copyright © 2018年 stoneobs.qq.com. All rights reserved.
//

#import "VCHomeViewController.h"
#import "NSBundle+STSystemTool.h"
#import "AVAsset+STTools.h"
#define MediaFileName @"export.mp4"
@interface VCHomeViewController ()<TZImagePickerControllerDelegate>
@property(nonatomic, strong) UIView                     *header;/**< <##> */
@property(nonatomic, strong) STButton                     *item1Button;/**< <##> */
@property(nonatomic, strong) STButton                     *item2Button;/**<  */
@property(nonatomic, strong) STButton                     *item3Button;/**< <##> */

@property(nonatomic, strong) NSString                     *item1OutPutPath;/**< <##> */
@property(nonatomic, strong) NSString                     *item2OutPutPath;/**< <##> */
@property(nonatomic, strong) NSString                     *item3OutPutPath;/**< <##> */

@property(nonatomic, strong) NSString                     *finshOutPutPath;/**<最终*/
@property(nonatomic, strong) AVAsset                     *frontAsset;/**< <##> */
@property(nonatomic, strong) AVAsset                     *backAsset;/**< <##> */


@property(nonatomic, strong) AVURLAsset                     *outputAsset;/**< 合成后的视屏 在合成音乐 */
@property(nonatomic, strong) AVURLAsset                     *audioAsset;/**< <##> */


@end

@implementation VCHomeViewController
//- (BOOL)prefersStatusBarHidden{
//    return YES;
//}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"首页";
    [self st_setRightItemWithTitle:@"导出" titleColor:UIColor.whiteColor];
    self.view.backgroundColor = [UIColor colorWithGradientStyle:UIGradientStyleTopToBottom withFrame:UIScreenFrame andColors:@[FlatOrange,FlatCoffee,FlatMint]];
    
    [self configSubView];
    [self st_setLeftItemWithTitle:@"合并" titleColor:UIColor.whiteColor];
    
    NSURL * path = [NSURL fileURLWithPath:[[VCBgmManger manger] urlWithName:@"出场霸气"]];
    NSURL * audioUrl =  path;
    AVURLAsset* audioAsset = [[AVURLAsset alloc] initWithURL:audioUrl options:nil];
    self.audioAsset = audioAsset;
    [self.audioAsset whenProperties:@[@"tracks"] areReadyDo:^{
        
    }];
    // Do any additional setup after loading the view.
}
#pragma mark --subView
- (void)configSubView{
    
    UIView * header = [[UIView alloc] initWithFrame:CGRectMake(10, 120, UIScreenWidth - 20, (UIScreenWidth - 20) * 0.75)];
    header.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:header];
    
    CGFloat itemHeight = (header.height - 20)/2;
    
    self.item1Button = [self defultButton];
    self.item1Button.frame = CGRectMake(10, 10, header.width - 20, itemHeight);
    [header addSubview:self.item1Button];
    
    
    self.item2Button = [self defultButton];
    self.item2Button.frame = CGRectMake(10, 10 + _item1Button.bottom, (header.width - 30)/2, itemHeight);
    [header addSubview:self.item2Button];
    
    self.item3Button = [self defultButton];
    self.item3Button.frame = CGRectMake(10 + _item2Button.right, 10 + _item1Button.bottom, (header.width - 20)/2, itemHeight);
    [header addSubview:self.item3Button];
    
    
    self.header = header;
}
- (STButton*)defultButton{
    __weak typeof(self) weakSelf =  self;
    STButton * buyButton = [[STButton alloc] initWithFrame:CGRectZero
                                                     title:nil
                                                titleColor:nil
                                                 titleFont:0
                                              cornerRadius:0
                                           backgroundColor:BACKROUND_COLOR
                                           backgroundImage:DefultAddImage
                                                     image:nil];
    [buyButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelctedAddButton:sender];
    }];
    return buyButton;
}
- (void)st_rightBarAction:(id)sender{
//    if (_item1 && _item2 && _item3) {
//        [SVProgressHUD showInfoWithStatus:@"正在从icloud下载视频"];
//    }
    
    [self shareToDucment];

}
- (void)st_leftBarAction:(id)sender{
    [self judgeCanMerge];
}
- (void)shareToDucment{
    if (self.item1OutPutPath.length) {
        NSString * path = self.item1OutPutPath;
        if (self.finshOutPutPath) {
            path = self.finshOutPutPath;
        }
        NSURL *urlToShare = [NSURL fileURLWithPath:path];
        NSArray *activityItems = @[urlToShare];
        
//        UIVideoEditorController * videoEditor = [UIVideoEditorController new];
//        videoEditor.view.backgroundColor = UIColor.whiteColor;
//        videoEditor.videoMaximumDuration = 30;
//        videoEditor.videoPath = self.finshOutPutPath;
//        [self presentViewController:videoEditor animated:YES completion:nil];
//        return;
        
        UIActivityViewController *controller = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:nil];
        [controller setCompletionWithItemsHandler:^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
            if (activityError) {
                [SVProgressHUD showErrorWithStatus:activityError.description];
            }
        }];
        [self presentViewController:controller animated:YES completion:nil];
    }
}
#pragma mark --Action Method
- (void)onSelctedAddButton:(UIButton*)sender{
    
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:4 columnNumber:4 delegate:self pushPhotoPickerVc:YES];
    
#pragma mark - 五类个性化设置，这些参数都可以不传，此时会走默认设置
    imagePickerVc.isSelectOriginalPhoto = YES;
    imagePickerVc.allowTakePicture = YES; // 在内部显示拍照按钮
    imagePickerVc.allowTakeVideo = YES;   // 在内部显示拍视频按
    imagePickerVc.videoMaximumDuration = 10; // 视频最大拍摄时间
    [imagePickerVc setUiImagePickerControllerSettingBlock:^(UIImagePickerController *imagePickerController) {
        imagePickerController.videoQuality = UIImagePickerControllerQualityTypeHigh;
    }];
    
    
    imagePickerVc.iconThemeColor = [UIColor colorWithRed:31 / 255.0 green:185 / 255.0 blue:34 / 255.0 alpha:1.0];
    imagePickerVc.showPhotoCannotSelectLayer = YES;
    imagePickerVc.cannotSelectLayerColor = [[UIColor whiteColor] colorWithAlphaComponent:0.8];
    [imagePickerVc setPhotoPickerPageUIConfigBlock:^(UICollectionView *collectionView, UIView *bottomToolBar, UIButton *previewButton, UIButton *originalPhotoButton, UILabel *originalPhotoLabel, UIButton *doneButton, UIImageView *numberImageView, UILabel *numberLabel, UIView *divideLine) {
        [doneButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    }];
    /*
     [imagePickerVc setAssetCellDidSetModelBlock:^(TZAssetCell *cell, UIImageView *imageView, UIImageView *selectImageView, UILabel *indexLabel, UIView *bottomView, UILabel *timeLength, UIImageView *videoImgView) {
     cell.contentView.clipsToBounds = YES;
     cell.contentView.layer.cornerRadius = cell.contentView.tz_width * 0.5;
     }];
     */
    
    // 3. Set allow picking video & photo & originalPhoto or not
    // 3. 设置是否可以选择视频/图片/原图
    imagePickerVc.allowPickingVideo = YES;
    imagePickerVc.allowPickingImage = YES;
    imagePickerVc.allowPickingOriginalPhoto = YES;
    imagePickerVc.allowPickingGif = NO;
    imagePickerVc.allowPickingMultipleVideo = YES; // 是否可以多选视频
    
    // 4. 照片排列按修改时间升序
    imagePickerVc.sortAscendingByModificationDate = YES;
    
    // imagePickerVc.minImagesCount = 3;
    // imagePickerVc.alwaysEnableDoneBtn = YES;
    
    // imagePickerVc.minPhotoWidthSelectable = 3000;
    // imagePickerVc.minPhotoHeightSelectable = 2000;
    
    /// 5. Single selection mode, valid when maxImagesCount = 1
    /// 5. 单选模式,maxImagesCount为1时才生效
    imagePickerVc.showSelectBtn = NO;
    imagePickerVc.statusBarStyle = UIStatusBarStyleLightContent;
    // 设置是否显示图片序号
    imagePickerVc.showSelectedIndex = YES;
    
#pragma mark - 到这里为止
    
    // You can get the photos by block, the same as by delegate.
    // 你可以通过block或者代理，来得到用户选择的照片.
    
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        
        
        PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
        options.version = PHImageRequestOptionsVersionCurrent;
        options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;
        options.networkAccessAllowed = true;
        PHAsset *realAseet = assets.firstObject;
        NSInteger phassetsecends  = [realAseet duration];
        if (phassetsecends> 180) {
            [SVProgressHUD showInfoWithStatus:@"选择视频最多三分钟哦"];
            return ;
        }
        
        
        [sender setBackgroundImage:photos.firstObject forState:UIControlStateNormal];
        if (sender == self.item1Button) {
            self.item1OutPutPath = nil;
        }
        if (sender == self.item2Button) {
            self.item2OutPutPath = nil;
        }
        if (sender == self.item3Button) {
            self.item3OutPutPath = nil;
        }

        PHAsset * aseet = assets.firstObject;
        if (aseet.mediaType ==  PHAssetMediaTypeImage ) {
            [[TZImageManager manager] getOriginalPhotoWithAsset:assets.firstObject completion:^(UIImage *photo, NSDictionary *info) {
                if (![info[PHImageResultIsDegradedKey] boolValue]) {
                    //原图
                    NSInteger rand = arc4random()%100000000000 + 1000000000;
                    NSString * outputPath = [NSString stringWithFormat:@"%@/%ld.png",NSBundle.st_documentDirectoryPath,rand];
                    bool success =  [UIImagePNGRepresentation(photo) writeToFile:outputPath atomically:YES]; // 保存成功会返回YES
                    if (sender == self.item1Button) {
                        self.item1OutPutPath = outputPath;
                    }
                    if (sender == self.item2Button) {
                        self.item2OutPutPath = outputPath;
                    }
                    if (sender == self.item3Button) {
                        self.item3OutPutPath = outputPath;
                    }
                    if (self.item1OutPutPath.length && self.item2OutPutPath.length) {
                        [self judgeCanMerge];
                    }
                }
            }];
        }else{
            [[TZImageManager manager] getVideoOutputPathWithAsset:assets.firstObject success:^(NSString *outputPath) {
                
                if (sender == self.item1Button) {
                    self.item1OutPutPath = outputPath;
//                    [self testMeargMusic];
                }
                if (sender == self.item2Button) {
                    self.item2OutPutPath = outputPath;
                }
                if (sender == self.item3Button) {
                    self.item3OutPutPath = outputPath;
                }
                if (self.item1OutPutPath.length && self.item2OutPutPath.length) {
                    [self judgeCanMerge];
                }
                
            } failure:^(NSString *errorMessage, NSError *error) {
                
            }];
        }


        
    }];
    
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}
#pragma mark --Private Method
- (void)judgeCanMerge{
    AVAsset * topAsset = [AVAsset assetWithURL:[NSURL fileURLWithPath:self.item1OutPutPath]];
    [topAsset whenProperties:@[@"tracks"] areReadyDo:^{
        self.frontAsset = topAsset;
        if (self.frontAsset && self.backAsset) {
            [self mergeVideoTest];
        }
    }];
    
    AVAsset * bootomAsset = [AVAsset assetWithURL:[NSURL fileURLWithPath:self.item2OutPutPath]];
    
    [bootomAsset whenProperties:@[@"tracks"] areReadyDo:^{
        self.backAsset = bootomAsset;
        if (self.frontAsset && self.backAsset) {
            [self mergeVideoTest];
        }
    }];
}
- (void)mergeVideoTest{

    //将两个视屏加入到处理器
    AVMutableComposition *composition = [AVMutableComposition  composition];
    [self addAsset:self.frontAsset toComposition:composition withTrackID:1];
    [self addAsset:self.backAsset toComposition:composition withTrackID:2];
    
    AVAssetTrack    *frontVideoTrack = _frontAsset.firstVideoTrack;
    
    AVAssetTrack    *backVideoTrack = _backAsset.firstVideoTrack;
    
    AVMutableVideoComposition *videoComposition = [AVMutableVideoComposition videoComposition];
    
    CGFloat  width = 1000;
    CGFloat  height = width * 0.75;
    //视频渲染大小为4：3
    videoComposition.renderSize =  CGSizeMake(width, width * 3 / 4);;
    // 一帧 需要的时间
    videoComposition.frameDuration = CMTimeMakeWithSeconds(1.0 / frontVideoTrack.nominalFrameRate, backVideoTrack.naturalTimeScale);
    
    CMTimeShow(videoComposition.frameDuration);
    //frameDuration  视屏时长 CMTimeMake(25, 600) 代表 每一秒 600帧，（人眼看成视屏最低帧率24帧 每秒，有的视屏是25，30 取最小公倍数，为600，25则为 视屏时长，）
    
    
    CMTime videoTime = self.backAsset.duration;
    NSInteger videoLength = videoTime.value / videoTime.timescale;
    
    CMTime musicTime = self.frontAsset.duration;
    NSInteger musicLength = musicTime.value / musicTime.timescale;
    
    videoComposition.frameDuration = CMTimeMake(MIN(videoLength, musicLength), 600);
    
    
    AVMutableVideoCompositionInstruction *instruction = [AVMutableVideoCompositionInstruction videoCompositionInstruction];
    //背景色设置
    
    instruction.backgroundColor = FlatMint.CGColor;
    instruction.timeRange = [composition.tracks.firstObject timeRange];

    AVMutableVideoCompositionLayerInstruction *frontLayerInstruction = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstruction];

//    CALayer * layer = CALayer.layer;
//    layer.cornerRadius = 40;
//    frontLayerInstruction.tool

    [frontLayerInstruction setTransform:CGAffineTransformMakeScale(width /2/ frontVideoTrack.naturalSize.width, width *3 / 4 / frontVideoTrack.naturalSize.height) atTime:kCMTimeZero];
    
    frontLayerInstruction.trackID = 1;
    
    
    AVMutableVideoCompositionLayerInstruction *backLayerInstruction = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstruction];
    
    backLayerInstruction.trackID = 2;

    
    [backLayerInstruction setTransform:CGAffineTransformMakeTranslation(width /2,0)atTime:kCMTimeZero];
    CGSize size;
    for (AVAssetTrack *track in self.frontAsset.tracks) {
        size  = track.naturalSize;
    }
    CGSize tosize = CGSizeMake(width/2, height - 200);
    CGAffineTransform tranceform = CGAffineTransformMakeTranslation(width /2,0);
    [backLayerInstruction setTransform:tranceform atTime:kCMTimeZero];
    [backLayerInstruction setTransform:CGAffineTransformScale(tranceform, tosize.width/size.width, tosize.height/size.height) atTime:kCMTimeZero];
    
    //左右画面
    
    instruction.layerInstructions = @[ frontLayerInstruction, backLayerInstruction ];
    
    videoComposition.instructions = @[ instruction ];
    
    //添加图片
    
    CALayer * waterLayer = CALayer.layer;
    CALayer * parentLayer = CALayer.layer;
    CALayer * videoLayer = CALayer.layer;
    
     CALayer * testLayer = CALayer.layer;
    
    parentLayer.backgroundColor = UIColor.whiteColor.CGColor;
    videoLayer.backgroundColor = UIColor.whiteColor.CGColor;
    
    parentLayer.frame = CGRectMake(0, 0, videoComposition.renderSize.width, videoComposition.renderSize.height);
    videoLayer.frame = CGRectMake(0, 0, videoComposition.renderSize.width, videoComposition.renderSize.height);
    
    testLayer.frame = CGRectMake(10, 10, width/2, height /2 -15);
    testLayer.cornerRadius = 20;
    testLayer.masksToBounds = YES;
    
    [parentLayer addSublayer:testLayer];
    
    videoLayer.cornerRadius = 100;
    videoLayer.masksToBounds = YES;
    videoLayer.backgroundColor = FlatOrange.CGColor;
    
    [parentLayer addSublayer:videoLayer];
    
    waterLayer.frame = CGRectMake(width - (width - 20)/2, 10, (width - 20)/2, 180);
    waterLayer.backgroundColor = FlatRed.CGColor;
    waterLayer.cornerRadius = waterLayer.frame.size.height/2;
    waterLayer.masksToBounds = YES;
    
    //
    [waterLayer setContents:[UIImage imageNamed:@"banner_scene_7"].CGImage];
    [parentLayer addSublayer:waterLayer];
    
    videoComposition.animationTool = [AVVideoCompositionCoreAnimationTool videoCompositionCoreAnimationToolWithPostProcessingAsVideoLayer:videoLayer inLayer:parentLayer];
    
    //合成音乐
    


    AVAssetExportSession *exporter = [AVAssetExportSession exportSessionWithAsset:composition presetName:AVAssetExportPresetHighestQuality];
    
    NSString *urlPath = [NSBundle.st_documentDirectoryPath stringByAppendingPathComponent:@"export.mp4"];
    NSFileManager * fileManager = NSFileManager.defaultManager;
    if ([fileManager fileExistsAtPath:urlPath]) {
        [fileManager removeItemAtPath:urlPath error:nil];
    }
    
    exporter.outputURL = [NSURL fileURLWithPath:urlPath];
    
    exporter.outputFileType = AVFileTypeMPEG4;
    
    exporter.shouldOptimizeForNetworkUse = YES;
    
    exporter.videoComposition = videoComposition;
    
    [exporter exportAsynchronouslyWithCompletionHandler:^{
        
        self.finshOutPutPath = urlPath;
        AVAssetExportSessionStatus status = exporter.status;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            NSLog(@"导出%ld",status);
            if (status == AVAssetExportSessionStatusCompleted) {
                //
                NSLog(@"视频已经合成，正在合成音乐");
                AVURLAsset* videoAsset = [[AVURLAsset alloc] initWithURL:[NSURL fileURLWithPath:urlPath] options:nil];
                self.outputAsset = videoAsset;
                [self testMeargMusic];
            }
            NSLog(@"%@",exporter.error);
            switch (status) {
                    
                case  AVAssetExportSessionStatusCompleted:{

                    
                    
                    break;
                }
                    
                caseAVAssetExportSessionStatusFailed:{
                    
                    break;
                    
                }
                    
                    
                    
                default:
                    
                    break;
                    
            }

        });
 
    }];
}
- (void)addAsset:(AVAsset *)asset toComposition:(AVMutableComposition *)composition withTrackID:(CMPersistentTrackID)trackID {
    
    AVMutableCompositionTrack *videoTrack = [composition  addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:trackID];
    
    CMTimeRange timeRange;
    
    if (CMTimeGetSeconds(_frontAsset.duration) > CMTimeGetSeconds(_backAsset.duration)) {
        
        timeRange = CMTimeRangeFromTimeToTime(kCMTimeZero,_backAsset.duration);
        
    }else{
        
        timeRange = CMTimeRangeFromTimeToTime(kCMTimeZero,_frontAsset.duration);
        
    }
    
    AVAssetTrack *assetVideoTrack = asset.firstVideoTrack;
    
    [videoTrack insertTimeRange:timeRange ofTrack:assetVideoTrack atTime:kCMTimeZero error:nil];
    
}

- (void)testMeargMusic{
    
    //AVURLAsset此类主要用于获取媒体信息，包括视频、声音等
    NSURL * videoUrl =  [NSURL fileURLWithPath:self.item1OutPutPath];
    
    NSArray * array =  VCBgmManger.manger.allBgm;
    NSInteger index = arc4random()%(array.count-1);
    NSURL * path = [NSURL fileURLWithPath:[VCBgmManger realPath:array[index]]];
    NSURL * audioUrl =  path;
    AVURLAsset* audioAsset = [[AVURLAsset alloc] initWithURL:audioUrl options:nil];
    
    AVURLAsset* videoAsset = self.outputAsset;
    NSRange videoRange = NSMakeRange(0, self.outputAsset.duration.value / self.outputAsset.duration.timescale);
    
    //创建AVMutableComposition对象来添加视频音频资源的AVMutableCompositionTrack
    AVMutableComposition* mixComposition = [AVMutableComposition composition];
    
    //CMTimeRangeMake(start, duration),start起始时间，duration时长，都是CMTime类型
    //CMTimeMake(int64_t value, int32_t timescale)，返回CMTime，value视频的一个总帧数，timescale是指每秒视频播放的帧数，视频播放速率，（value / timescale）才是视频实际的秒数时长，timescale一般情况下不改变，截取视频长度通过改变value的值
    //CMTimeMakeWithSeconds(Float64 seconds, int32_t preferredTimeScale)，返回CMTime，seconds截取时长（单位秒），preferredTimeScale每秒帧数
    
    //开始位置startTime
    CMTime startTime = CMTimeMakeWithSeconds(videoRange.location, videoAsset.duration.timescale);
    //截取长度videoDuration
    CMTime videoDuration = CMTimeMakeWithSeconds(videoRange.length, videoAsset.duration.timescale);
    
    CMTimeRange videoTimeRange = CMTimeRangeMake(startTime, videoDuration);
    
    //视频采集compositionVideoTrack
    AVMutableCompositionTrack *compositionVideoTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
    
#warning 避免数组越界 tracksWithMediaType 找不到对应的文件时候返回空数组
    //TimeRange截取的范围长度
    //ofTrack来源
    //atTime插放在视频的时间位置
    [compositionVideoTrack insertTimeRange:videoTimeRange ofTrack:([videoAsset tracksWithMediaType:AVMediaTypeVideo].count>0) ? [videoAsset tracksWithMediaType:AVMediaTypeVideo].firstObject : nil atTime:kCMTimeZero error:nil];

    
    
    
    
    //音频采集compositionCommentaryTrack

    
    
    CMTime videoTime = videoAsset.duration;
    NSInteger videoLength = videoTime.value / videoTime.timescale;
    
    CMTime musicTime = audioAsset.duration;
    NSInteger musicLength = musicTime.value / musicTime.timescale;
    
    NSLog(@"video时间 %ld  音乐时间%ld",videoLength,musicLength);
    NSInteger max = videoLength / musicLength + 1;
    for (NSInteger i = 0; i < max; i ++ ) {
        //无限循环背景音乐 此方法 行不通，考虑 多次  合成音频 新的视频文件中
        AVMutableCompositionTrack *compositionAudioTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid ];

        NSURL * path = [NSURL fileURLWithPath:[[VCBgmManger manger] urlWithName:@"出场霸气"]];
        NSURL * audioUrl =  path;
        AVURLAsset* tempaudioAsset = [[AVURLAsset alloc] initWithURL:audioUrl options:nil];
        
        CMTime musicstartTime = CMTimeMakeWithSeconds( i * musicLength, tempaudioAsset.duration.timescale);
        //截取长度videoDuration
        NSInteger endintergerTime = i * musicLength + musicLength;
//        if (endintergerTime > videoLength) {
//           endintergerTime = endintergerTime >  videoLength?videoLength:endintergerTime;
//
//        }
        endintergerTime = endintergerTime >  videoLength?videoLength:endintergerTime;
        CMTime musicendTime = CMTimeMakeWithSeconds(endintergerTime , tempaudioAsset.duration.timescale);
        
        CMTimeRange tmpvideoTimeRange = CMTimeRangeMake(musicstartTime, musicendTime);
        NSLog(@"i = %ld  range---",i);
        CMTimeRangeShow(tmpvideoTimeRange);
        
        NSError * musiceror = nil;
        [compositionAudioTrack insertTimeRange:tmpvideoTimeRange
                                       ofTrack:([tempaudioAsset tracksWithMediaType:AVMediaTypeAudio].count > 0) ? [tempaudioAsset tracksWithMediaType:AVMediaTypeAudio].firstObject : nil
                                        atTime:kCMTimeZero
                                         error:&musiceror];
        NSLog(@"musiceror = %@",musiceror);
    }
    
    //AVAssetExportSession用于合并文件，导出合并后文件，presetName文件的输出类型
    AVAssetExportSession *assetExportSession = [[AVAssetExportSession alloc] initWithAsset:mixComposition presetName:AVAssetExportPresetHighestQuality];
    
    NSString *outPutPath = [NSTemporaryDirectory() stringByAppendingPathComponent:MediaFileName];
    //混合后的视频输出路径
    NSURL *outPutUrl = [NSURL fileURLWithPath:outPutPath];
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:outPutPath])
    {
        [[NSFileManager defaultManager] removeItemAtPath:outPutPath error:nil];
    }
    
    //输出视频格式 AVFileTypeMPEG4 AVFileTypeQuickTimeMovie...
    assetExportSession.outputFileType = AVFileTypeMPEG4;
    //    NSArray *fileTypes = assetExportSession.
    
    assetExportSession.outputURL = outPutUrl;
    //输出文件是否网络优化
    assetExportSession.shouldOptimizeForNetworkUse = YES;
    
    [assetExportSession exportAsynchronouslyWithCompletionHandler:^{
        self.finshOutPutPath = outPutUrl.description;
        AVAssetExportSessionStatus status = assetExportSession.status;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            NSLog(@"导出%ld",status);
            NSLog(@"%@",assetExportSession.error);
            switch (status) {
                    
                case AVAssetExportSessionStatusCompleted:{
                    NSLog(@"音乐已经合成");
                    break;
                }
                    
                case AVAssetExportSessionStatusFailed:{
                    
                    break;
                    
                }
                    
                    
                    
                default:
                    
                    break;
                    
            }
            
        });
    }];
}
@end

